package com.greejoy.score.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.greejoy.score.MyApplication;
import com.greejoy.score.R;
import com.greejoy.score.domain.BaseBody;
import com.greejoy.score.domain.MatchValue;
import com.greejoy.score.domain.ScoreInfo;
import com.greejoy.score.domain.ScoreInfoBody;
import com.greejoy.score.service.HttpService;
import com.greejoy.score.utils.DimUtils;
import com.greejoy.score.utils.ScoreUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import okhttp3.ResponseBody;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ScoreActivity extends AppCompatActivity implements View.OnClickListener {

    private ScoreInfo scoreInfo;
    private Long judgeId;
    private String judgeName;
    private MyApplication app;
    private Retrofit retrofit;
    private HttpService httpService;

    private TextView tv_logout;
    private long submitLastClickTime = 0;
    private long logoutLastClickTime = 0;

    private TextView tv_item_info;
    private TextView tv_judge_info;
    private TextView tv_player_info;

    LinearLayout ll_value_list;

    private TextView tv_score;

    private Map<Integer, MatchValue> viewMatchValueMap;
    private Integer currValueScoreTextViewId;

    private Button btn_score_1;
    private Button btn_score_2;
    private Button btn_score_3;
    private Button btn_score_4;
    private Button btn_score_5;
    private Button btn_score_6;
    private Button btn_score_7;
    private Button btn_score_8;
    private Button btn_score_9;
    private Button btn_score_clear;
    private Button btn_score_0;
    private Button btn_score_dot;
    private Button btn_score_up;
    private Button btn_score_down;

    private boolean isSubmitting = false;
    private Button btn_submit_score;

    private GifImageView giv_ws_loading;

    private Callback submitCallBack = new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if(response.isSuccessful()){
                try {
                    BaseBody baseBody = JSON.parseObject(response.body().string(), BaseBody.class);
                    if(baseBody.getCode() == 0){
                        Toast.makeText(ScoreActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(ScoreActivity.this, "提交失败-" + baseBody.getMsg(), Toast.LENGTH_LONG).show();
                    }
                } catch (IOException e) {
                    Toast.makeText(ScoreActivity.this, "错误-" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(ScoreActivity.this, "提交失败-" + t.getMessage(), Toast.LENGTH_LONG).show();
        }
    };

    private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(getString(R.string.broadcast_action))){
                String msg = intent.getStringExtra("msg");
                switch (msg){
                    case "showWsLoading":
                        giv_ws_loading.setVisibility(View.VISIBLE);
                        break;
                    case "hideWsLoading":
                        giv_ws_loading.setVisibility(View.INVISIBLE);
                        break;
                }
            }
        }
    };

    @Override
    public void onBackPressed() {
        // 屏蔽返回
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        refreshContent();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(getString(R.string.broadcast_action));
        registerReceiver(myBroadcastReceiver, intentFilter);

        Bundle bundle = getIntent().getExtras();
        judgeId = bundle.getLong("judge_id");
        judgeName = bundle.getString("judge_name");

        tv_item_info = findViewById(R.id.tv_item_info);
        tv_judge_info = findViewById(R.id.tv_judge_info);
        tv_player_info = findViewById(R.id.tv_player_info);

        ll_value_list = findViewById(R.id.ll_value_list);

        btn_submit_score = findViewById(R.id.btn_submit_score);
        btn_submit_score.setOnClickListener(this);

        // 分数
        tv_score = findViewById(R.id.tv_score);
        btn_score_1 = findViewById(R.id.btn_score_1);
        btn_score_1.setOnClickListener(this);
        btn_score_2 = findViewById(R.id.btn_score_2);
        btn_score_2.setOnClickListener(this);
        btn_score_3 = findViewById(R.id.btn_score_3);
        btn_score_3.setOnClickListener(this);
        btn_score_4 = findViewById(R.id.btn_score_4);
        btn_score_4.setOnClickListener(this);
        btn_score_5 = findViewById(R.id.btn_score_5);
        btn_score_5.setOnClickListener(this);
        btn_score_6 = findViewById(R.id.btn_score_6);
        btn_score_6.setOnClickListener(this);
        btn_score_7 = findViewById(R.id.btn_score_7);
        btn_score_7.setOnClickListener(this);
        btn_score_8 = findViewById(R.id.btn_score_8);
        btn_score_8.setOnClickListener(this);
        btn_score_9 = findViewById(R.id.btn_score_9);
        btn_score_9.setOnClickListener(this);
        btn_score_clear = findViewById(R.id.btn_score_clear);
        btn_score_clear.setOnClickListener(this);
        btn_score_0 = findViewById(R.id.btn_score_0);
        btn_score_0.setOnClickListener(this);
        btn_score_dot = findViewById(R.id.btn_score_dot);
        btn_score_dot.setOnClickListener(this);
        btn_score_up = findViewById(R.id.btn_score_up);
        btn_score_up.setOnClickListener(this);
        btn_score_down = findViewById(R.id.btn_score_down);
        btn_score_down.setOnClickListener(this);

        tv_logout = findViewById(R.id.tv_logout);
        tv_logout.setOnClickListener(this);

        giv_ws_loading = findViewById(R.id.giv_ws_loading);

        app = MyApplication.getInstance();
        String httpUrl = app.dataMap.get("httpUrl");
        retrofit = new Retrofit.Builder().baseUrl(httpUrl).build();
        httpService = retrofit.create(HttpService.class);

        refreshContent();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_logout) {
            if (System.currentTimeMillis() - logoutLastClickTime < 500) {
                finish();
                Intent intent = new Intent(ScoreActivity.this, MainActivity.class);
                startActivity(intent);
            }
            logoutLastClickTime = System.currentTimeMillis();
        }
        else if (v.getId() == R.id.btn_submit_score) {

            if (!isSubmitting && System.currentTimeMillis() - submitLastClickTime < 500) {

                List<MatchValue> matchValueList = viewMatchValueMap.values().stream().collect(Collectors.toList());
                if(matchValueList.stream().filter(f -> f.getScore() == null).count() > 0){
                    Toast.makeText(ScoreActivity.this, "请完成所有打分再提交", Toast.LENGTH_SHORT).show();
                    return;
                }

                isSubmitting = true;
                // 提交服务器
                String valueStr = JSON.toJSONString(matchValueList);
                httpService.saveScore(getString(R.string.server_key), judgeId, valueStr).enqueue(submitCallBack);

                // 跳转等待页
                finish();
                Intent intent = new Intent(ScoreActivity.this, WaitingActivity.class);
                intent.putExtra("judge_name", judgeName);
                startActivity(intent);
            }
            submitLastClickTime = System.currentTimeMillis();
        } else if (v.getId() == R.id.btn_score_up) {
            prevValueScoreTextView();
        } else if (v.getId() == R.id.btn_score_down) {
            nextValueScoreTextView();
        } else if (v.getId() == R.id.btn_score_1) {
            valueScoreChange("1");
        } else if (v.getId() == R.id.btn_score_2) {
            valueScoreChange("2");
        } else if (v.getId() == R.id.btn_score_3) {
            valueScoreChange("3");
        } else if (v.getId() == R.id.btn_score_4) {
            valueScoreChange("4");
        } else if (v.getId() == R.id.btn_score_5) {
            valueScoreChange("5");
        } else if (v.getId() == R.id.btn_score_6) {
            valueScoreChange("6");
        } else if (v.getId() == R.id.btn_score_7) {
            valueScoreChange("7");
        } else if (v.getId() == R.id.btn_score_8) {
            valueScoreChange("8");
        } else if (v.getId() == R.id.btn_score_9) {
            valueScoreChange("9");
        } else if (v.getId() == R.id.btn_score_clear) {
            valueScoreChange("clear");
        } else if (v.getId() == R.id.btn_score_0) {
            valueScoreChange("0");
        } else if (v.getId() == R.id.btn_score_dot) {
            valueScoreChange(".");
        }
    }

    private void scoreChange(String key) {
        String score_str = "0.0";
        if(key.equals("clear")){
            score_str = "0.0";
        }else {
            String txt = tv_score.getText().toString();
            // 只允许存在一个小数点
            if(txt.contains(".") && key.equals(".")){
                return;
            }
            // 只允许包含2位小数
            if(txt.split("\\.").length > 1 && txt.split("\\.")[1].length() == 2){
                return;
            }

            if(txt.equals("0") && !key.equals(".")){
                score_str = key;
            }else {
                score_str = txt + key;
            }
        }
        tv_score.setText(score_str);
    }

    private void nextValueScoreTextView() {
        List<Integer> viewIds = viewMatchValueMap.entrySet().stream().map(Map.Entry::getKey).sorted(Integer::compareTo).collect(Collectors.toList());
        for (Integer viewId : viewIds) {
            findViewById(viewId).setBackgroundColor(getColor(R.color.gray));
        }
        int nextIndex = 0;
        if (currValueScoreTextViewId != null) {
            for (int i = 0; i < viewIds.size(); i++) {
                if (currValueScoreTextViewId == viewIds.get(i)) {
                    if (i < viewIds.size() - 1) {
                        nextIndex = i + 1;
                    }else {
                        nextIndex = viewIds.size() - 1;
                    }
                    break;
                }
            }
        }
        currValueScoreTextViewId = viewIds.get(nextIndex);
        findViewById(currValueScoreTextViewId).setBackgroundColor(getColor(R.color.blue));
    }

    private void prevValueScoreTextView() {
        List<Integer> viewIds = viewMatchValueMap.entrySet().stream().map(Map.Entry::getKey).sorted(Integer::compareTo).collect(Collectors.toList());
        for (Integer viewId : viewIds) {
            findViewById(viewId).setBackgroundColor(getColor(R.color.gray));
        }
        int nextIndex = 0;
        if (currValueScoreTextViewId != null) {
            for (int i = 0; i < viewIds.size(); i++) {
                if (currValueScoreTextViewId == viewIds.get(i)) {
                    if (i != 0) {
                        nextIndex = i - 1;
                    }
                    break;
                }
            }
        }
        currValueScoreTextViewId = viewIds.get(nextIndex);
        findViewById(currValueScoreTextViewId).setBackgroundColor(getColor(R.color.blue));
    }

    private void valueScoreChange(String key) {
        TextView tv = findViewById(currValueScoreTextViewId);
        MatchValue matchValue = viewMatchValueMap.get(currValueScoreTextViewId);

        if (tv != null && matchValue != null) {
            if(key.equals("clear")){
                tv.setText("");
                matchValue.setScore(null);
            }else {
                String valueScoreStr = "0";
                String txt = tv.getText().toString();
                // 只允许存在一个小数点 不能直接按点
                if(key.equals(".") && (txt.contains(".") || txt.equals(""))){
                    Toast.makeText(ScoreActivity.this, "请输入有效数字", Toast.LENGTH_SHORT).show();
                    return;
                }
                // 只允许包含1位小数
                if(txt.split("\\.").length > 1 && txt.split("\\.")[1].length() == 1){
                    Toast.makeText(ScoreActivity.this, "支持小数点后一位", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(txt.equals("0") && !key.equals(".")){
                    valueScoreStr = key;
                }else {
                    valueScoreStr = txt + key;
                }

                // 大于最大值
                Double score = Double.valueOf(valueScoreStr);
                if(score > matchValue.getValue()){
                    Toast.makeText(ScoreActivity.this, "最大分值为" + matchValue.getValue() + "分", Toast.LENGTH_SHORT).show();
                    return;
                }
                matchValue.setScore(score);
                tv.setText(valueScoreStr);

                // 输入小数后自动下一项
                if(valueScoreStr.split("\\.").length > 1 && valueScoreStr.split("\\.")[1].length() == 1){
                    nextValueScoreTextView();
                }
            }
        }

        // 计算总分
        Double scoreCount = 0d;
        for (Map.Entry<Integer, MatchValue> entry : viewMatchValueMap.entrySet()) {
            if(entry.getValue().getScore() != null){
                scoreCount += entry.getValue().getScore();
            }
        }
        tv_score.setText(ScoreUtils.roundDoubleValueStr(scoreCount, 1));
    }

    private void refreshContent() {
        scoreChange("clear");
        httpService.getScoreInfo(getString(R.string.server_key), judgeId).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        String bodyStr = response.body().string();
                        ScoreInfoBody scoreInfoBody = JSON.parseObject(bodyStr, ScoreInfoBody.class);
                        scoreInfo = scoreInfoBody.getData();
                        tv_item_info.setText(scoreInfo.getItemInfo());
                        tv_judge_info.setText(judgeName);
                        tv_player_info.setText(scoreInfo.getPlayerInfo());

                        List<MatchValue> valueList = scoreInfo.getMatchValueList();
                        ll_value_list.removeAllViews();
                        viewMatchValueMap = new HashMap<>();

                        int dp10 = DimUtils.dip2px(ScoreActivity.this, 10);
                        for (int i = 0; i < valueList.size(); i++) {
                            TextView tv;

                            MatchValue val = valueList.get(i);
                            LinearLayout ll = new LinearLayout(ScoreActivity.this);
                            ll.setGravity(Gravity.CENTER);
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                            params.setMargins(dp10 * 2, dp10 / 2, 0, dp10 / 2);
                            ll.setLayoutParams(params);

                            tv = new TextView(ScoreActivity.this);
                            tv.setText(val.getName() + " (" + val.getValue() + "分)");
                            tv.setTextColor(getColor(R.color.black));
                            tv.setTextSize(16);
                            tv.setWidth(dp10 * 12);
                            ll.addView(tv);


                            tv = new TextView(ScoreActivity.this);
                            int id = View.generateViewId();
                            viewMatchValueMap.put(id, val);
                            tv.setId(id);
                            tv.setGravity(Gravity.CENTER);
                            tv.setWidth(dp10 * 6);
                            tv.setHeight(dp10 * 4);
                            tv.setBackgroundColor(getColor(R.color.gray));
                            tv.setTextColor(getColor(R.color.white));
                            tv.setTextSize(20);
                            tv.setOnClickListener(v -> {
                                List<Integer> viewIds = viewMatchValueMap.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toList());
                                for (Integer viewId : viewIds) {
                                    findViewById(viewId).setBackgroundColor(getColor(R.color.gray));
                                }
                                currValueScoreTextViewId = v.getId();
                                v.setBackgroundColor(getColor(R.color.blue));
                            });
                            ll.addView(tv);

                            ll_value_list.addView(ll);
                        }

                        currValueScoreTextViewId = null;
                        nextValueScoreTextView();

                    } catch (Exception e) {
                        Toast.makeText(ScoreActivity.this, e.getMessage(), Toast.LENGTH_LONG);
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText(ScoreActivity.this, t.getMessage(), Toast.LENGTH_LONG);
            }
        });
    }

}